<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogTableVisible" :before-close="cancel" width="30%">
      <el-form :model="form">
        <el-form-item label="标签项名称" :label-width="formLabelWidth" class="inputWidth">
          <el-input v-model="form.labelName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="标签颜色" :label-width="formLabelWidth">
          <el-color-picker v-model="form.color"></el-color-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { labelAdd, labelDetail, labelUpdate } from 'api/label'
export default {
  props: ['labelId', 'show', 'labelGroupId'],
  data() {
    return {
      dialogTableVisible: false,
      title: '新增标签项',
      formLabelWidth: '100px',
      form: {
        labelGroupId: this.labelGroupId,
        labelName: '',
        color: null
      }
    }
  },
  watch: {
    show(val, oldval) {
      if (val === true) {
        if (this.labelId) {
          this.getLabelDetail()
          this.title = '编辑标签项'
        } else {
          this.title = '新增标签项'
        }
        this.dialogTableVisible = true
      } else if (val === false) {
        this.dialogTableVisible = false
      }
    }
  },
  methods: {
    async getLabelDetail() {
      try {
        let back = await labelDetail(this.labelId)
        back = back.data
        if (back.resultCode === '200') {
          this.form.labelName = back.result.labelName
          this.form.color = back.result.color
        } else {
          this.$alert(back.msg)
        }
      } catch (err) {
        this.$alert('请求出错', '提示')
      }
    },
    async submit() {
      if (this.labelId) {
        this.updateLabel()
      } else {
        this.addLabel()
      }
    },
    async addLabel() {
      this.form.labelGroupId = this.labelGroupId
      try {
        let back = await labelAdd(this.form)
        back = back.data
        console.log(back)
        this.$emit('updateList')
        this.cancel()
      } catch (err) {
        this.$alert('请求出错', '提示')
      }
    },
    async updateLabel(row) {
      try {
        const parm = { ...this.form }
        parm.labelId = this.labelId
        let back = await labelUpdate(parm)
        back = back.data
        if (back.resultCode === '200') {
          this.$emit('updateList')
          this.cancel()
        } else {
          this.$alert(back.msg)
        }
      } catch (err) {
        this.$alert('请求出错', '提示')
      }
    },
    cancel() {
      this.form.labelGroupId = ''
      this.form.labelName = ''
      this.form.color = null
      this.$emit('cancelDialog')
    }
  }
}
</script>
<style lang="scss" scoped>
  .inputWidth{
    width:90%;
  }
</style>
